const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const globs = require('globs');

function containsJSX(code) {
  try {
    const ast = parser.parse(code, {
      sourceType: 'module',
      plugins: ['jsx']
    });

    let hasJSX = false;
    // 简单遍历 AST 查找 JSXElement 节点
    const visit = (node) => {
      if (!node || hasJSX) return;
      if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
        hasJSX = true;
        return;
      }
      for (const key in node) {
        const child = node[key];
        if (Array.isArray(child)) {
          child.forEach(visit);
        } else if (child && typeof child === 'object') {
          visit(child);
        }
      }
    };

    visit(ast);
    return hasJSX;
  } catch (err) {
    console.error('Parse error:', err);
    return false;
  }
}

// 示例文件夹遍历（你自己实现递归）
const folder = '/Users/xiaodian/Desktop/earth/src/**/*.js';
globs(folder, function (err, files) {
  if (err) {
    throw err;
  }
  files.forEach((file) => {
    if (file.endsWith('.js')) {
      const code = fs.readFileSync(file, 'utf-8');
      if (containsJSX(code)) {
        fs.renameSync(file, file.replace(/\.js$/, '.tsx'));
        console.log(`Renamed ${file} -> ${file.replace(/\.js$/, '.tsx')}`);
      } else {
        fs.renameSync(file, file.replace(/\.js$/, '.ts'));
        console.log(`Renamed ${file} -> ${file.replace(/\.js$/, '.ts')}`);
      }
    }
  })
});
